package com.company;


import com.alibaba.csb.sdk.HttpCaller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class Fun_g extends JPanel implements CallBack {

    JTextField t1, t2, t3, t4, t5;
    String s1, s2, s3, s4, s5;
    String[] strings = new String[]{"操作员:", "操作编号:", "班次:", "班组:"};
    JLabel showLable1, showLable2;
    JTextArea jt, jt2;
    AtomicInteger show1 = new AtomicInteger(0);
    AtomicInteger show2 = new AtomicInteger(0);
    JComboBox<String> box;
    List<GUser> users;
    private SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private SimpleDateFormat sf2 = new SimpleDateFormat("yyyyMMddHH");

    public Fun_g() {
        super(new BorderLayout());
        users = SqliteTools.queryData();
        add(getTop(), BorderLayout.NORTH);
        add(getEditPanel(), BorderLayout.WEST);
        add(getCenterPanel());
        if (users.size() != 0) {
            GUser u = users.get(0);
            t1.setText(u.getS1());
            t2.setText(u.getS2());
            t3.setText(getS3(u.getS4()));
            t4.setText(u.getS4());
        }
    }

    public JPanel getTop() {
        JPanel jPanel = new JPanel();
        JLabel filler = new JLabel("当前业务:勾核          用户:");
        filler.setFont(new Font("楷体", Font.TYPE1_FONT, 20));
        filler.setForeground(Color.RED);
        jPanel.add(filler);
        box = new JComboBox<>();
        if (users.size() == 0) {
            box.addItem("--暂无用户--");
        } else {
            for (GUser u : users) {
                box.addItem(u.getS1());
            }
        }
        box.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                int i = box.getSelectedIndex();
                if (i == users.size()) i = i - 1;
                if (users.size() != 0 && i < users.size()) {
                    GUser u = users.get(i);
                    t1.setText(u.getS1());
                    t2.setText(u.getS2());
                    t3.setText(getS3(u.getS4()));
                    t4.setText(u.getS4());
                }
            }
        });
        jPanel.add(box);
        return jPanel;
    }

    private String getS3(String s4) {
        String format = sf2.format(new Date());
        return format + s4;
    }

    public void startSocket() {
        new Thread() {
            @Override
            public void run() {
                SocketUtils.start(Fun_g.this::back);
            }
        }.start();
    }

    public void closeSocket() {
        SocketUtils.close();
        show1.set(0);
        show2.set(0);
        jt.setText("");
        jt2.setText("");
    }

    private JPanel getEditPanel() {
        JPanel panel = new JPanel();
        panel.setLayout(new FlowLayout());
        panel.add(getLoginPanel());
        return panel;
    }

    private JPanel getLoginPanel() {
        JPanel panel = new JPanel();
        TitledBorder titledBorder = BorderFactory.createTitledBorder("登录信息");
        titledBorder.setTitleJustification(TitledBorder.TOP);
        panel.setBorder(titledBorder);
        panel.setLayout(new BorderLayout());
        panel.add(getLoingInput());
        JPanel jPanel = new JPanel();
        JButton button = new JButton("添加用户");
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                s1 = t1.getText();
                s2 = t2.getText();
                s3 = t3.getText();
                s4 = t4.getText();
                if (TextUtils.isEmpty(s1) || TextUtils.isEmpty(s2) || TextUtils.isEmpty(s3) || TextUtils.isEmpty(s4)) {
                    JOptionPane.showMessageDialog(null, "输入有空，请检查后重新添加.");
                    return;
                }
                int i = JOptionPane.showConfirmDialog(null, "确定要添加用户吗？", "添加提示", 0);
                if (i == 0) {
                    SqliteTools.insertGUser(s1, s2, s3, s4);
                    GUser u = new GUser();
                    u.setS1(s1);
                    u.setS2(s2);
                    u.setS3(s3);
                    u.setS4(s4);
                    if (users.size() == 0) {
                        box.removeItem("--暂无用户--");
                    }
                    box.addItem(s1);
                    users.add(u);
                    box.setSelectedItem(s1);
                    JOptionPane.showMessageDialog(null, "添加成功");
                } else {
                    JOptionPane.showMessageDialog(null, "添加取消");
                }
            }
        });
        jPanel.add(button);
        JButton delete = new JButton("删除用户");
        delete.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (users.size() == 0) {
                    JOptionPane.showMessageDialog(null, "暂无用户无法删除");
                    return;
                }
                GUser user = users.get(box.getSelectedIndex());
                int i = JOptionPane.showConfirmDialog(null, "确定要删除用户 " + user.getS1() + " 吗？", "删除提示", 0);
                if (i == 0) {
                    SqliteTools.deleteGuser(user);
                    users.remove(user);
                    box.removeItem(user.getS1());
                    if (users.size() == 0) {
                        box.addItem("--暂无用户--");
                        t1.setText("");
                        t2.setText("");
                        t3.setText("");
                        t4.setText("");
                    }
                    box.setSelectedIndex(0);
                    JOptionPane.showMessageDialog(null, "删除成功");
                } else {
                    JOptionPane.showMessageDialog(null, "删除取消");
                }
            }
        });
        jPanel.add(delete);
        JButton create = new JButton("生成班次");
        create.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                s4 = t4.getText();
                if (TextUtils.isEmpty(s4)) {
                    JOptionPane.showMessageDialog(null, "请先输入班组信息，再点击生成班次");
                    return;
                }
                t3.setText(getS3(s4));
            }
        });
        jPanel.add(create);
        JButton start = new JButton("开始勾核");
        start.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                s1 = t1.getText();
                s2 = t2.getText();
                s3 = t3.getText();
                s4 = t4.getText();
                if (TextUtils.isEmpty(s1) || TextUtils.isEmpty(s2) || TextUtils.isEmpty(s3) || TextUtils.isEmpty(s4)) {
                    JOptionPane.showMessageDialog(null, "输入有空，请检查后重新启动.");
                    return;
                }
                int i = JOptionPane.showConfirmDialog(null, "请仔细检查登录信息，确定要" +
                        "启动吗？", "启动提示", 0);
                if (i == 0) {
                    closeSocket();
                    JOptionPane.showMessageDialog(null, "启动成功");
                    TabbedPane.closeP();//开启勾核时关闭配发
                    startSocket();
                } else {
                    JOptionPane.showMessageDialog(null, "启动取消");
                }
            }
        });
        jPanel.add(start);
        panel.add(jPanel, BorderLayout.SOUTH);
        return panel;
    }

    private JPanel getLoingInput() {
        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(4, 1, 1, 5));
        panel.add(getLablePanel(strings[0]));
        panel.add(getLablePanel(strings[1]));
        panel.add(getLablePanel(strings[2]));
        panel.add(getLablePanel(strings[3]));
        return panel;
    }

    private JPanel getLablePanel(String text) {
        JPanel panel = new JPanel();
        JLabel label = new JLabel(text);
        label.setForeground(Color.RED);
        JPanel j = new JPanel();
        j.setPreferredSize(new Dimension(60, 30));
        j.add(label);
        panel.add(j);

        panel.add(getTextFieldPanel(text));
        return panel;
    }

    private JPanel getTextFieldPanel(String text) {
        JPanel panel = new JPanel();
        JTextField label = new JTextField();
        label.setColumns(20);
        panel.add(label);
        if (text.equals(strings[0])) {
            t1 = label;
        } else if (text.equals(strings[1])) {
            t2 = label;
        } else if (text.equals(strings[2])) {
            t3 = label;
        } else if (text.equals(strings[3])) {
            t4 = label;
        } else if (text.equals("单号:")) {
            t5 = label;
        }
        return panel;
    }

    private JPanel getCenterPanel() {
        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
//        panel.setLayout(new GridLayout(6, 1, 1, 10));
        panel.add(getCenterInputPanel(), BorderLayout.NORTH);
        panel.add(getBottomPanle(), BorderLayout.SOUTH);
//        panel.add(setZero());
        panel.add(getArea());
        return panel;
    }

    private JPanel getArea() {
        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(1, 2, 1, 1));
        panel.add(getShowArea());
        panel.add(getShowArea2());
        return panel;
    }

    private JScrollPane getShowArea() {
        jt = new JTextArea();
        jt.setEnabled(true);
//        jt.setForeground(Color.BLUE);
//        jt.setFont(new Font("楷体", Font.TYPE1_FONT, 15));
        JScrollPane js = new JScrollPane(jt);
        js.setVerticalScrollBarPolicy(
                JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        TitledBorder titledBorder = BorderFactory.createTitledBorder("正常日志");
        titledBorder.setTitleJustification(TitledBorder.LEFT);
        js.setBorder(titledBorder);
        return js;
    }

    private JScrollPane getShowArea2() {
        jt2 = new JTextArea();
        jt2.setEnabled(true);
//        jt.setForeground(Color.BLUE);
//        jt.setFont(new Font("楷体", Font.TYPE1_FONT, 15));
        JScrollPane js = new JScrollPane(jt2);
        js.setVerticalScrollBarPolicy(
                JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        TitledBorder titledBorder = BorderFactory.createTitledBorder("异常日志");
        titledBorder.setTitleJustification(TitledBorder.LEFT);
        js.setBorder(titledBorder);
        return js;
    }

    private JPanel getBottomPanle() {
        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(2, 1, 1, 5));
        panel.add(getShowPanelRight());
        panel.add(setZero());
        return panel;
    }

    private JPanel getShowPanelRight() {
        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(2, 1));
        //正常
        JPanel right = new JPanel();
        {
            JLabel label = new JLabel();
            label.setText("正常:");
            right.add(label);
            showLable1 = new JLabel();
            showLable1.setText("0");
            right.add(showLable1);
        }
        panel.add(right);
        //异常
        JPanel wrong = new JPanel();
        {
            JLabel label1 = new JLabel();
            label1.setText("异常:");
            wrong.add(label1);
            showLable2 = new JLabel();
            showLable2.setText("0");
            wrong.add(showLable2);
        }
        panel.add(wrong);
        return panel;
    }


    private JPanel setZero() {
        JPanel panel = new JPanel();
        JButton jButton = new JButton("清零");
        jButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                show1.set(0);
                show2.set(0);
                showLable1.setText(show1.toString());
                showLable2.setText(show2.toString());
            }
        });
        panel.add(jButton);
        return panel;
    }

    private JPanel getCenterInputPanel() {
        JPanel panel = new JPanel();
        TitledBorder titledBorder = BorderFactory.createTitledBorder("手动录入");
        titledBorder.setTitleJustification(TitledBorder.TOP);
        panel.setBorder(titledBorder);
        panel.add(getLablePanel("单号:"));
        JButton button = new JButton("录入");
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (TextUtils.isEmpty(s1) || TextUtils.isEmpty(s2) || TextUtils.isEmpty(s3) || TextUtils.isEmpty(s4)) {
                    JOptionPane.showMessageDialog(null, "还未录入并保存基础信息，请保存基础信息后重试");
                    return;
                }
                s5 = t5.getText();
                if (TextUtils.isEmpty(s5)) {
                    JOptionPane.showMessageDialog(null, "输入有空，请检查后重新录入.");
                    return;
                }
                int i = JOptionPane.showConfirmDialog(null, "确定要录入吗？", "录入提示", 0);
                if (i == 0) {
                    JOptionPane.showMessageDialog(null, "输入成功");
                    upData(s5);
                } else {
                    JOptionPane.showMessageDialog(null, "输入取消");
                }
                t5.setText("");
                s5 = "";
            }
        });
        panel.add(button);
        return panel;
    }

    String shopCode, shopName, opOrgCode, opOrgName;
    String url, ak, sk, sysCode, password;

    private void upData(String text) {
        new Thread() {
            @Override
            public void run() {
                Map<String, String> map = new HashMap<>();
                Map<String, Object> query = getQuery();
                query.put("waybillNo", text);
                String s = JSON.toJSONString(query);
                map.put("query", s);
                Map<String, Object> header = getHeader();
                header.put("sign", SignUtils.getSign(password, s));
                map.put("messageHeader", JSON.toJSONString(header));
                System.out.println(JSON.toJSONString(map));
                try {
                    int i = 1;
                    String result = HttpCaller.doPost(url, "sortScanInfoCheck", "1.0.0", map, ak, sk);
                    System.out.println(result);
                    JSONObject jsonObject = JSON.parseObject(result);
                    if (jsonObject.containsKey("code") && jsonObject.getInteger("code") == 200) {
                        JSONObject body = jsonObject.getJSONObject("body");
                        if (body.getString("retCode").equals("000") && body.getBoolean("retBody")) {
                            i = 1;
                        } else {
                            i = 2;
                        }
                    } else {
                        i = 2;
                    }
                    inputResult(i, text);
                    SqliteTools.insertData(false, "勾核", text, i == 2 ? "异常" : "正常", s3, s4, s1, s2);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }

    private void inputResult(int i, String text) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                if (i == 2) {
                    jt2.append("\n异常:" + text + "");
                    show2.incrementAndGet();
                    showLable2.setText(show2.toString());
                } else {
                    jt.append("\n正常:" + text);
                    show1.incrementAndGet();
                    showLable1.setText(show1.toString());
                }
            }
        });
        if (i == 2) bee();
    }

    Map<String, Object> header = new HashMap<>();

    public Map<String, Object> getHeader() {
        header.put("serialNo", UUID.randomUUID().toString());
        header.put("sendDate", sf.format(new Date()));
        header.put("sysCode", sysCode);
        return header;
    }

    @Override
    public void back(Object result) {
        upData(result.toString());
    }


    Map<String, Object> query = null;

    private Map<String, Object> getQuery() {
        if (shopCode == null || shopName == null || opOrgCode == null || opOrgName == null || url == null || ak == null ||
                sk == null || sysCode == null || password == null) {
            getProperties();
        }
        if (query == null) {
            query = new HashMap<>();
            query.put("shopCode", shopCode);
            query.put("shopName", shopName);
            query.put("opOrgCode", opOrgCode);
            query.put("opOrgName", opOrgName);
            query.put("userName", s1);
            query.put("userCode", s2);
            query.put("shiftNo", s3);
            query.put("workGroupNo", s4);
        }
        return query;
    }

    private void getProperties() {
        Properties pro = readPropertiesFile("/g.properties");
        shopCode = pro.getProperty("shopCode", "");
        shopName = pro.getProperty("shopName", "");
        opOrgCode = pro.getProperty("opOrgCode", "");
        opOrgName = pro.getProperty("opOrgName", "");
        Properties pro2 = readPropertiesFile("/config.properties");
        url = pro2.getProperty("url", "http://10.4.191.246:8086/csb_jidi1_1");
        ak = pro2.getProperty("ak", "");
        sk = pro2.getProperty("sk", "");
        sysCode = pro2.getProperty("sysCode", "");
        password = pro2.getProperty("password", "");
    }

    /**
     * 读Properties文件
     */
    private Properties readPropertiesFile(String path) {
        Properties prop = new Properties();
        InputStream in = null;
        try {
            in = this.getClass().getResourceAsStream(path);
            //prop.load(in);//直接这么写，如果properties文件中有汉子，则汉字会乱码。因为未设置编码格式。
            prop.load(new InputStreamReader(in, "utf-8"));
            for (String key : prop.stringPropertyNames()) {
                System.out.println(key + ":" + prop.getProperty(key));
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    System.out.println(e.getMessage());
                }
            }
        }
        return prop;
    }

    public void bee() {
        Frame f = new Frame();
        Toolkit kit = f.getToolkit();
        kit.beep();
    }

}
